package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.govern.gateway.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Aniymx on 2019/1/13 18:12.
 */
@Component
public class LoginFilter extends ZuulFilter {
    @Autowired
    private AuthService authService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 2;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletResponse response = currentContext.getResponse();
        HttpServletRequest request = currentContext.getRequest();
        String tokenFromCookie = authService.getTokenFromCookie(request);
        //从cookie中进行查询
        if (tokenFromCookie==null){
            this.access_denied();
        }
        //从redis中校验身份令牌是否过期
        long expire = authService.getExpire(tokenFromCookie);
        if (expire<=0){
            this.access_denied();
        }

        //取出authorization中的内容
        String jwtFromHeader = authService.getJwtFromHeader(request);
        if (jwtFromHeader==null) {
            this.access_denied();
        }


        return null;
    }

    private void access_denied() {
        RequestContext currentContext = RequestContext.getCurrentContext();
//拒绝访问
        currentContext.setSendZuulResponse(false);
        //设置响应的状态码
        currentContext.setResponseStatusCode(200);

        ResponseResult responseResult = new ResponseResult(CommonCode.UNAUTHORISE);
        String jsonString = JSON.toJSONString(responseResult);
        currentContext.setResponseBody(jsonString);
        currentContext.getResponse().setContentType("application/json;charset=UTF-8");
    }


}
